Skip to content

For await of ​

本节目标:理解“For await of”的核心思路,并能把它用于实际开发或面试表达。 for await…of 前面介绍过,for...of循环用于遍历同步的 Iterator 接口。新引入的for await...of循环,则是用于遍历异步的 Iterator 接口。

  1. async function f() {
  2.  for await (const x of createAsyncIterable(['a', 'b'])) {
  3.  console.log(x);
  4. }

  5. }

  6. // a

  7. // b

上面代码中,createAsyncIterable()返回一个拥有异步遍历器接口的对象,for...of循环自动调用这个对象的异步遍历器的next方法,会得到一个 Promise 对象。await用来处理这个 Promise 对象,一旦resolve,就把得到的值(x)传入for...of的循环体。 for await...of循环的一个用途,是部署了 asyncIterable 操作的异步接口,可以直接放入这个循环。 12. let body = '';

  1. async function f() {
  2. for await(const data of req) body += data;
  3. const parsed = JSON.parse(body);
  4. console.log('got', parsed);
  5. }

上面代码中,req是一个 asyncIterable 对象,用来异步读取数据。可以看到,使用for await...of循环以后,代码会非常简洁。 如果next方法返回的 Promise 对象被reject,for await...of就会报错,要用try...catch捕捉。 20. async function () {

  1. try {
  2. for await (const x of createRejectingIterable()) {
  3. console.log(x);
  4. }

  5. } catch (e) {
  6. console.error(e);
  7. }

  8. }

注意,for await...of循环也可以用于同步遍历器。 31. (async function () {

  1. for await (const x of ['a', 'b']) {
  2. console.log(x);
  3. }

  4. })();

  5. // a

  6. // b

Node v10 支持异步遍历器,Stream 就部署了这个接口。下面是读取文件的传统写法与异步遍历器写法的差异。 40. // 传统写法 41. function main(inputFilePath) {

  1. const readStream = fs.createReadStream(
  2. inputFilePath,
  3. { encoding: 'utf8', highWaterMark: 1024 }
  4. );

  5. readStream.on('data', (chunk) => {
  6. console.log('>>> '+chunk);
  7. });

  8. readStream.on('end', () => {
  9. console.log('### DONE ###');
  10. });

  11. }

  12. // 异步遍历器写法

  13. async function main(inputFilePath) {
  14. const readStream = fs.createReadStream(
  15. inputFilePath,
  16. { encoding: 'utf8', highWaterMark: 1024 }
  17. );

  18. for await (const chunk of readStream) {
  19. console.log('>>> '+chunk);
  20. }

  21. console.log('### DONE ###');
  22. } > 来自 <https://www.bookstack.cn/read/es6-3rd/spilt.3.docs-async-iterator.md> > 来自 <https://www.bookstack.cn/read/es6-3rd/spilt.3.docs-async-iterator.md>